package com.it.facade;

import cn.dev33.satoken.util.SaResult;
import cn.hutool.json.JSONUtil;
import com.it.auth.LoginInfoDTO;
import com.it.auth.WxInfoDTO;
import com.it.auth.WxInfoVo;
import com.it.config.AppProperties;
import com.it.service.LoginService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.LinkedHashMap;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/app/login")
@RequiredArgsConstructor
public class AppLoginController {

    private final LoginService loginService;

    private final AppProperties appProperties;

    private final RestTemplate restTemplate;

    @PostMapping("/wechat")
    public SaResult login(@RequestBody WxInfoDTO wxInfoDTO) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        LinkedHashMap<String, String> params = new LinkedHashMap<>();
        params.put("appid", appProperties.getWxAppId());
        params.put("secret", appProperties.getWxSecret());
        params.put("js_code", wxInfoDTO.getCode());
        params.put("grant_type", appProperties.getWxGrantType());
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        params.forEach(builder::queryParam);
        URI uri = builder.build().encode().toUri();
        String wxInfoVoJson = restTemplate.getForObject(uri, String.class);
        WxInfoVo wxInfoVo = JSONUtil.toBean(wxInfoVoJson, WxInfoVo.class);
        if (Objects.nonNull(wxInfoVo) && StringUtils.isNotEmpty(wxInfoVo.getOpenid())) {
            //从数据库查询openId相关的用户
            // 生成token
            LoginInfoDTO loginInfoDTO = new LoginInfoDTO();
            String openid = wxInfoVo.getOpenid();
            loginInfoDTO.setWxOpenId(openid);
            return loginService.wxLogin(loginInfoDTO,wxInfoDTO);
        } else {
            throw new RuntimeException(Objects.requireNonNull(wxInfoVo).getErrmsg());
        }
    }

    @PostMapping("/token")
    public SaResult token(@RequestBody LoginInfoDTO loginInfoDTO) {
        log.info("app登录信息:{}", JSONUtil.toJsonStr(loginInfoDTO));
        return loginService.login(loginInfoDTO);
    }
}
